<template>
  <div>
    <div class="form1">
      <el-form ref="ruleForm" :model="userInfo" status-icon :rules="rules" label-width="100px">
        <el-row type="flex" class="flex1">
          <el-col :span="9">
            <el-form-item label="工号" prop="workNumber">
              <el-input v-model="userInfo.workNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="入职时间" prop="timeOfEntry">
              <el-date-picker
                v-model="userInfo.timeOfEntry"
                type="date"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="flex1">
          <el-col :span="9">
            <el-form-item label="姓名" prop="username">
              <el-input v-model="userInfo.username" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="部门" prop="departmentName">
              <el-input v-model="userInfo.departmentName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="flex1">
          <el-col :span="9">
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="userInfo.mobile" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="聘用形式" prop="formOfEmployment">
              <el-select v-model="userInfo.formOfEmployment" class="select" placeholder="请选择聘用形式">
                <el-option label="正式" :value="1" />
                <el-option label="非正式" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="24">
            <el-form-item label="员工头像">
              <img style="display: none" :src="userInfo.staffPhoto" alt="" @error="error">
              <el-upload
                :class="{upload: fileList.length}"
                action="#"
                list-type="picture-card"
                :limit="1"
                :file-list="fileList"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-change="handleChange"
                :http-request="handleRequest"
                :before-upload="beforeUpload"
              >
                <i class="el-icon-plus" />
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
              <el-progress v-if="progress" :percentage="percent" style="width: 190px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">保存更新</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    <span>基础信息</span>
    <div class="form1">
      2
    </div>
  </div>
</template>

<script>
import { getEmployeeList, setUser } from '@/api/employees'
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDObXCbniMjpdBSTEivsYw3uUnoY1D8l8E',
  SecretKey: 'qPikVzC8nAG5dutc4F9l7C3dx0lFSO2P'
})
export default {
  props: ['userInfo', 'total'],
  data() {
    const checkPhoto = (rule, value, callback) => {
      if (/^1[3-9]\d{9}$/.test(value)) return callback()
      callback(new Error('手机号格式错误'))
    }
    const checkWorkNumber = async(rule, value, callback) => {
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      const flag = rows.some(item => (this.userInfo.id !== item.id) && (item.workNumber === value))
      if (flag) {
        return callback(new Error('该工号已被使用，请重新输入'))
      }
      callback()
    }
    const checkTimeOfEntry = (rule, value, callback) => {
      if (this.userInfo.correctionTime) {
        const timer1 = new Date(this.userInfo.timeOfEntry).getTime() // 入职时间
        const timer2 = new Date(this.userInfo.correctionTime).getTime() // 转正时间
        if (timer1 > timer2) return callback(new Error('日期错误'))
      }
      callback()
    }
    return {
      fileList: [{ url: this.userInfo.staffPhoto }], // 图片地址设置为数组
      dialogVisible: false, // 是否浏览图片
      dialogImageUrl: '',
      currentFileUid: '', // 用来保存上传文件的id
      percent: 0,
      progress: false,
      rules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhoto, trigger: 'blur' }
        ],
        formOfEmployment: [
          { required: true, message: '请输入选择聘用形式', trigger: 'change' }
        ],
        workNumber: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { validator: checkWorkNumber, trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '请选择入职时间', trigger: 'blur' },
          { validator: checkTimeOfEntry, trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请输入部门称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleChange(file, fileList) {
      console.log(file)
      this.fileList.push(file)
    },
    handleRequest(params) {
      // console.log(params)
      if (params.file) {
        // 执行上传操作
        cos.putObject({
          Bucket: '123456-1309145479', // 存储桶
          Region: 'ap-nanjing', // 地域
          Key: params.file.name, // 文件名
          Body: params.file, // 要上传的文件对象
          StorageClass: 'STANDARD', // 上传的模式类型 直接默认 标准模式即可
          // 上传到腾讯云 =》 哪个存储桶 哪个地域的存储桶 文件  格式  名称 回调
          // 正在上传函数 得到上传进度
          onProgress: progressData => { /* 非必须 */
            // console.log(progressData)
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          // data返回数据之后 应该如何处理
          console.log(err || data)
          if (!err && data.statusCode === 200) {
            // 此时说明文件上传成功  要获取成功的返回地址
            // fileList才能显示到上传组件上 此时我们要将fileList中的数据的url地址变成 现在上传成功的地址
            // 目前虽然是一张图片 但是请注意 我们的fileList是一个数组
            // 需要知道当前上传成功的是哪一张图片
            this.fileList = this.fileList.map(item => {
              // 去找谁的uid等于刚刚记录下来的id
              if (item.uid === this.currentFileUid) {
                this.userInfo.staffPhoto = 'http://' + data.Location
                // 将成功的地址赋值给原来的url属性
                return { url: 'http://' + data.Location, upload: true }
                // upload 为true 表示这张图片已经上传完毕 这个属性要为我们后期应用的时候做标记
                // 保存  => 图片有大有小 => 上传速度有快又慢 =>要根据有没有upload这个标记来决定是否去保存
              }
              return item
            })
            setTimeout(() => {
              this.progress = false
              this.percent = 0
            }, 1000)
          }
        })
      }
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => item.upload === false)
      this.userInfo.staffPhoto = null
      cos.deleteObject({
        Bucket: '123456-1309145479', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: file.name /* 必须 */
      }, function(err, data) {
        console.log(err || data)
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const type = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!type.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      if (type.size > 5 * 1024 * 1024) {
        this.$message.error('上传的图片大小不能大于5M')
        return false
      }
      // 保存上传图片的id
      this.currentFileUid = file.uid
      this.progress = true
      return true
    },
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate(async(valid) => {
        if (valid) {
          try {
            console.log(this.userInfo)
            await setUser(this.userInfo)
            this.$message({
              type: 'success',
              message: '更新成功'
            })
          } catch (error) {
            this.$message({
              type: 'error',
              message: '更新失败'
            })
          }
        }
      })
    },
    error(a) {
      this.fileList.splice(0, 1, { url: 'http://localhost:8888/static/img/head.b6c3427d.jpg' })
    }
  }
}
</script>

<style lang="scss" scoped>
.form1{
  padding: 0 100px;
}
.flex1{
  justify-content: space-between;
}
.select{
  width: 100%;
}
.upload{
  display: flex;
  height: 148px;
  ::v-deep .el-upload-list{
    li{
      margin: 0;
    }
  }
  ::v-deep .el-upload{
    display: none !important;
  }
}
::v-deep .el-dialog__header{
  height: 54px;
}
::v-deep .el-dialog__body {
  padding: 0;
  height: 427px;
}

</style>
